import requests
from datetime import datetime, timedelta

from flask import Flask


def last7day(today):
# 输出每天日期和对应的星期几（中文）
    weekdays_map = {
        'Monday': '周一',
        'Tuesday': '周二',
        'Wednesday': '周三',
        'Thursday': '周四',
        'Friday': '周五',
        'Saturday': '周六',
        'Sunday': '周日'
    }
    res = {}
    for i in range(7):
        # 计算当前日期
        current_date = today - timedelta(days=i)
        # 格式化日期
        formatted_date = current_date.strftime("%d")
        # 获取星期几（0为周一，6为周日）
        weekday = current_date.strftime("%A")
        # 将英文星期转换为中文
        chinese_weekday = weekdays_map.get(weekday)
        # 输出日期和星期几（中文）
        res["date"+str(i)] = formatted_date
        res["weekday"+str(i)] = chinese_weekday
    return res

# 定义请求接口1的函数
def request_interface1(code):
    url = "http://220.176.23.210:801/Retailing/LoadGoodsAssociateByCodeForApp"
    data = {
        "code": code,
        "nodeCode": "7005"
    }
    response = requests.post(url, json=data)
    return response.json()

# 定义请求接口2的函数
def request_interface2(ass_code):
    url = "http://220.176.23.210:801/Retailing/LoadGoodsPSSMSaleAmount"
    data = {
        "goodscode": ass_code,
        "nodecode": "7005"
    }
    response = requests.post(url, data=data)
    return response.json()

# 定义 goods_list
goods_list= [
    {"txm": "6910019016081", "name": "2.5kg超能APG薰衣草洗衣液+2.5kg超能APG薰衣草洗衣液N1"},
    {"txm": "6910019023324", "name": "2.38kg*2超能植沐悦色洗衣液"},
    {"txm": "6910019022563", "name": "860g超能内衣洗衣液"},
    {"txm": "6910019015503", "name": "101g*4超能女士内衣专用皂N1"},
    {"txm": "6970032250138", "name": "660g*2妙管家厨房重油污清洁剂N1"},
    {"txm": "6910019023416", "name": "凝珠系列产品(一季度政策单品)"},
]

# 创建 Flask 应用
app = Flask(__name__)

# 定义路由，响应 GET 请求
@app.route('/', methods=['GET'])
def get_text():
    # 获取当前日期
    today_date = datetime.now()

    table_html = """
        <html>
        <head>
            <title>商品信息</title>
            <style>
                table {{
                    border-collapse: collapse;
                    width: 100%;
                }}
                th, td {{
                    border: 1px solid #dddddd;
                    text-align: left;
                    padding: 8px;
                }}
                th {{
                    background-color: #f2f2f2;
                }}
                .today {{
                    color: red;
                }}
            </style>
        </head>
        <body>
            <h1>商品信息</h1>
            <table>
                <tr>
                    <th>商品名</th>
                    <th>条形码</th>
                    <th class="today">销量[今日]({date0}:{weekday0})</th>
                    <th>销量({date1}:{weekday1})</th>
                    <th>销量({date2}:{weekday2})</th>
                    <th>销量({date3}:{weekday3})</th>
                    <th>销量({date4}:{weekday4})</th>
                    <th>销量({date5}:{weekday5})</th>
                    <th>销量({date6}:{weekday6})</th>
                    <th>日期</th>
                </tr>
        """.format(**last7day(today_date))

    # 遍历 txm_list
    for good in goods_list:
        # 请求接口1
        response1 = request_interface1(good["txm"])
        ass_code = response1["obj"][0]["AssCode"]
        # 请求接口2
        response2 = request_interface2(ass_code)
        # SumSaleAmount 0-6 对应最近7天的销量，倒序排，今天11号
        good["sale"] = response2["obj"]["SumSaleAmount"]    # 11
        good["sale1"] = response2["obj"]["SumSaleAmount1"]  # 10
        good["sale2"] = response2["obj"]["SumSaleAmount2"]  # 9
        good["sale3"] = response2["obj"]["SumSaleAmount3"]  # 8
        good["sale4"] = response2["obj"]["SumSaleAmount4"]  # 7
        good["sale5"] = response2["obj"]["SumSaleAmount5"]  # 6
        good["sale6"] = response2["obj"]["SumSaleAmount6"]  # 5
        good["date"] = today_date.strftime("%Y-%m-%d")
        # 输出结果
        table_html += f"""
            <tr>
                <td>{good['name']}</td>
                <td>{good['txm']}</td>
                <td class="today">{good['sale']}</td>
                <td>{good['sale1']}</td>
                <td>{good['sale2']}</td>
                <td>{good['sale3']}</td>
                <td>{good['sale4']}</td>
                <td>{good['sale5']}</td>
                <td>{good['sale6']}</td>
                <td>{good['date']}</td>
            </tr>
        """
    table_html += """
        </table>
    </body>
    </html>"""
    return table_html

if __name__ == '__main__':
    # 启动 Flask 应用，监听 8666 端口
    app.run(host='0.0.0.0', port=8666)